package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderConfigMapper orderConfigMapper;


    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {

        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param order
     */
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public Orders findAllOrdersById(String id) {

        Orders orders = new Orders();

        Order order = orderMapper.selectByPrimaryKey(id);

        orders.setOrder(order);

        Example example = new Example(OrderItem.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("orderId",id);

        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

        orders.setOrderItems(orderItems);


        return orders;
    }

    /**
     * 批量发货
     * @param ids
     * @return
     */
    @Override
    public List<Order> handIngMany(String[] ids) {

        Example example = new Example(Order.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andIn("id", Arrays.asList(ids));

        criteria.andEqualTo("consignStatus","0");

        List<Order> orderList = orderMapper.selectByExample(example);

        return orderList;
    }

    /**
     * 确认发货
     * @param orderList
     */
    @Override
    public void sendOrders(List<Order> orderList) {

        OrderLog orderLog = new OrderLog();
        for (Order order : orderList) {
            if (order.getShippingCode()==null||order.getShippingCode()==null){
                throw new RuntimeException("请输入物流名称或者运单号");
            }else {
                order.setConsignStatus("1");//发货状态,已发货
                order.setOrderStatus("1");  //订单状态,已发货
                order.setConsignTime(new Date()); //发货时间
                orderMapper.updateByPrimaryKey(order); //修改状态


                //发货日志
                orderLog.setOrderStatus("1"); //订单状态，已发货
                orderLog.setConsignStatus("1");    //发货状态，已发货
                orderLog.setOperateTime(new Date());       //操作时间
                orderLog.setId(idWorker.nextId()+""); //生成操作日志信息id
                orderLog.setOperater("操作员");
                orderLog.setOrderId(Long.valueOf(order.getId())); //
                orderLog.setPayStatus(order.getPayStatus());     //支付状态
                orderLog.setRemarks(order.getTransactionId()); //支付流水号
                orderLogMapper.insert(orderLog);

            }
        }
    }

    //超时未付款关闭订单
    @Override
    public void normalOrder() {

        List<Order> orderList = orderMapper.selectAll();

        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);

        for (Order order : orderList) {

            long time = order.getCreateTime().getTime();

            if (orderConfig.getOrderTimeout()*60+time<new Date().getTime()){

                if ("0".equals(order.getOrderStatus())&&"0".equals(order.getPayStatus())&&"0".equals(order.getConsignStatus())){

                    orderMapper.deleteByPrimaryKey(order.getId());

                }
            }
        }
    }

    @Override
    public void seckillOrder() {

        List<Order> orderList = orderMapper.selectAll();

        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);

        for (Order order : orderList) {

            long time = order.getCreateTime().getTime();

            if (orderConfig.getSeckillTimeout()*60*1000+time<new Date().getTime()){

                if ("0".equals(order.getOrderStatus())&&"0".equals(order.getPayStatus())&&"0".equals(order.getConsignStatus())){

                orderMapper.deleteByPrimaryKey(order.getId());

                }

            }
        }


    }

    //自动收货
    @Override
    public void sendOvertime() {


        List<Order> orderList = orderMapper.selectAll();

        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);

        for (Order order : orderList) {

            long time = order.getCreateTime().getTime();

            if (orderConfig.getTakeTimeout()*24*60*60*1000+time<new Date().getTime()){

                if ("2".equals(order.getOrderStatus())&&"1".equals(order.getPayStatus())&&"1".equals(order.getConsignStatus())){

                    order.setOrderStatus("3");
                    orderMapper.updateByPrimaryKey(order);
                }

            }
        }





    }
    //自动结束交易订单
    @Override
    public void finishOrder() {

        List<Order> orderList = orderMapper.selectAll();

        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);

        for (Order order : orderList) {

            long time = order.getCreateTime().getTime();

            if (orderConfig.getServiceTimeout()*24*60*60*1000+time<new Date().getTime()){

                if ("2".equals(order.getOrderStatus())&&"1".equals(order.getPayStatus())&&"1".equals(order.getConsignStatus())){

                   order.setIsDelete("0");
                    orderMapper.updateByPrimaryKey(order);
                }

            }
        }

    }

    //自动五星好评
    @Override
    public void reputation() {

        List<Order> orderList = orderMapper.selectAll();

        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);

        for (Order order : orderList) {

            long time = order.getCreateTime().getTime();

            if (orderConfig.getCommentTimeout()*24*60*60*1000+time<new Date().getTime()){

                if ("2".equals(order.getOrderStatus())&&"1".equals(order.getPayStatus())&&"1".equals(order.getConsignStatus())){

                    order.setBuyerRate("1");
                    order.setBuyerMessage("五星好评");
                    orderMapper.updateByPrimaryKey(order);
                }

            }
        }

    }


    //订单合并
    @Override
    public void consolidate(String orderId1, String orderId2) {
        //order1  主订单   order2  从订单
        Order order1 = orderMapper.selectByPrimaryKey(orderId1);
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);


        order1.setTotalNum(order1.getTotalNum()+order2.getTotalNum());
        order1.setTotalMoney(order1.getTotalMoney()+order2.getTotalMoney());
        order1.setPayMoney(order1.getTotalNum()-order2.getTotalMoney());
        order1.setUpdateTime(new Date());

        orderMapper.updateByPrimaryKey(order1);
        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKey(order2);
    }

    @Override
    public void split(String id,Integer number) {

        Order order = orderMapper.selectByPrimaryKey(id);

        if (order.getTotalNum()<number){

            throw new RuntimeException("拆分数量超出最大能拆分的数量");

        }

        order.setTotalNum(order.getTotalNum()/number);//未÷尽为考虑
        order.setTotalMoney(order.getTotalMoney()/number);
        order.setPostFee(order.getPostFee()/number);
        order.setPayMoney(order.getPreMoney()/number);
        order.setUpdateTime(new Date());

        for (int i = 0; i < number - 1; i++) {

            order.setId(idWorker+"");
            order.setTotalNum(order.getTotalNum()/number);//未÷尽为考虑
            order.setTotalMoney(order.getTotalMoney()/number);
            order.setPostFee(order.getPostFee()/number);
            order.setPayMoney(order.getPreMoney()/number);
            order.setUpdateTime(new Date());
            orderMapper.insert(order);
        }
    }


    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */




    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
